package com.pd.backend.service.impl;

import com.google.common.collect.Maps;
import com.pd.backend.entity.PdAuthUser;
import com.pd.backend.dao.PdAuthUserDao;
import com.pd.backend.map.PdAuthUserMap;
import com.pd.backend.map.mapentity.GetSex;
import com.pd.backend.map.mapentity.PdAuthUserMapEntity;
import com.pd.backend.service.PdAuthUserService;

import com.pd.backend.utils.JwtUtils;
import com.pd.backend.vo.UserToken;
import com.pd.backend.vo.req.LoginReqVo;
import com.pd.backend.vo.resp.LoginRespVo;
import com.pd.backend.vo.resp.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.*;

/**
 * (PdAuthUser)表服务实现类
 *
 * @author GuoXinChao.126@gmail.com
 * @since 2023-02-27 17:14:32
 */
@Service("pdAuthUserService")
public class PdAuthUserServiceImpl implements PdAuthUserService {
    @Resource
    private PdAuthUserDao pdAuthUserDao;
    /**
     * 秘钥
     * - 默认aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt
     */
    // ${key:value}  value 是默认值，当我们从配置文件取key的值取到就是用取到的值。没取到则使用value的值！
    @Value("${secret:aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt}")
    private String secret;
    /**
     * 有效期，单位秒
     * - 默认2周
     */
    @Value("${expire-time-in-second:1209600}")
    private Long expirationTimeInSecond;

//    @Value("${permissionsList:  \"org:add\",\"role:config\",\"resource:add\",\"resource:update\"," +
//            "\"resource:delete\",\"org:update\",\"org:delete\",\"org:view\",\"org:import\"," +
//            "\"org:export\",\"station:add\",\"station:update\",\"station:delete\",\"station:view\"," +
//            "\"station:export\",\"station:import\",\"user:add\",\"user:update\",\"user:delete\"," +
//            "\"user:view\",\"user:import\",\"user:export\",\"menu:add\",\"menu:update\"," +
//            "\"menu:delete\",\"menu:view\",\"menu:export\",\"menu:import\",\"role:add\"," +
//            "\"role:update\",\"role:delete\",\"role:view\",\"role:export\",\"role:import\"," +
//            "\"role:auth\",\"optLog:view\",\"optLog:export\",\"optLog:delete\",\"loginLog:delete\"," +
//            "\"loginLog:export\",\"file:add\",\"file:update\",\"file:delete\",\"file:view\",\"file:download\"," +
//            "\"rule:config-view\",\"resource:view\",\"role:user-view\",\"loginLog:view\"," +
//            "\"attachment:view\",\"station:list\",\"view:list\",\"view:search\",\"view:show\"," +
//            "\"view:ydlist\",\"view:agencyDetail\",\"add:agency\",\"add:order\",\"view:transport\"," +
//            "\"view:pickup\",\"view:goodsTypeList\",\"view:truckTypeList\",\"add:truckType\"," +
//            "\"update:truckType\",\"delete:truckType\",\"view:truckTypeDetail\",\"view:carGoList\"," +
//            "\"view:orderCarGoList\",\"add:orderrCarGo\",\"view:fleet\",\"viewflletDetail\"," +
//            "\"add:fleet\",\"update:fleet\",\"delete:fleet\",\"add:goodsType\",\"update:goodsType\"," +
//            "\"view:goodsTypeDetail\",\"delete:goodsType\",\"view:courierList\",\"view:courierScope\"," +
//            "\"add:courierScope\",\"view:courierDetail\",\"view:truckList\",\"add:truck\"," +
//            "\"update:truck\",\"view:truckDetail\",\"view:truckLicense\",\"add:truckLicense\",\"delete:truck\"," +
//            "\"view:driverList\",\"view：driverDetail\",\"add:driver\",\"view:driverTruck\"," +
//            "\"add:driverLicense\",\"view:driverLicense\",\"view:lineTypeList\",\"add:transportLineType\"," +
//            "\"view:transportLineTypeDetail\",\"update:transportLineType\",\"delete:transportLineType\"," +
//            "\"view:transportLine\",\"add:transportLineManger\",\"delete:transportLine\"," +
//            "\"view:trips\",\"add:trips\",\"update:trips\",\"delete:trips\",\"view:tripsDetail\"," +
//            "\"add:tripsTruckDriver\",\"view:transportTaskManager\",\"view:transportTaskManagerDetail\"," +
//            "\"view:driverJobManager\",\"update:transportLineManage\",\"view:transportLineDetail\"," +
//            "\"view:scheduleList\",\"add:scheduleDispatch\",\"add:scheduleRun\",\"add:schedulePause\"," +
//            "\"add:scheduleResume\",\"add:driverInfo\",\"view:scheduleLog\",\"view:scheduleLogDetail\"," +
//            "\"view:truckTransportTrips\",\"add:taskManager\",\"view:queryLocus\",\"view:truckPlace\"," +
//            "\"view:truckPlaceInfo\",\"view:orderLocus\",\"view:selectByList\",\"view:orderLocusPoint\"," +
//            "\"view:taskPoint\"}")
    private String permissionsList =  "org:add\",\"role:config\",\"resource:add\",\"resource:update\"," +
            "\"resource:delete\",\"org:update\",\"org:delete\",\"org:view\",\"org:import\"," +
            "\"org:export\",\"station:add\",\"station:update\",\"station:delete\",\"station:view\"," +
            "\"station:export\",\"station:import\",\"user:add\",\"user:update\",\"user:delete\"," +
            "\"user:view\",\"user:import\",\"user:export\",\"menu:add\",\"menu:update\"," +
            "\"menu:delete\",\"menu:view\",\"menu:export\",\"menu:import\",\"role:add\"," +
            "\"role:update\",\"role:delete\",\"role:view\",\"role:export\",\"role:import\"," +
            "\"role:auth\",\"optLog:view\",\"optLog:export\",\"optLog:delete\",\"loginLog:delete\"," +
            "\"loginLog:export\",\"file:add\",\"file:update\",\"file:delete\",\"file:view\",\"file:download\"," +
            "\"rule:config-view\",\"resource:view\",\"role:user-view\",\"loginLog:view\"," +
            "\"attachment:view\",\"station:list\",\"view:list\",\"view:search\",\"view:show\"," +
            "\"view:ydlist\",\"view:agencyDetail\",\"add:agency\",\"add:order\",\"view:transport\"," +
            "\"view:pickup\",\"view:goodsTypeList\",\"view:truckTypeList\",\"add:truckType\"," +
            "\"update:truckType\",\"delete:truckType\",\"view:truckTypeDetail\",\"view:carGoList\"," +
            "\"view:orderCarGoList\",\"add:orderrCarGo\",\"view:fleet\",\"viewflletDetail\"," +
            "\"add:fleet\",\"update:fleet\",\"delete:fleet\",\"add:goodsType\",\"update:goodsType\"," +
            "\"view:goodsTypeDetail\",\"delete:goodsType\",\"view:courierList\",\"view:courierScope\"," +
            "\"add:courierScope\",\"view:courierDetail\",\"view:truckList\",\"add:truck\"," +
            "\"update:truck\",\"view:truckDetail\",\"view:truckLicense\",\"add:truckLicense\",\"delete:truck\"," +
            "\"view:driverList\",\"view：driverDetail\",\"add:driver\",\"view:driverTruck\"," +
            "\"add:driverLicense\",\"view:driverLicense\",\"view:lineTypeList\",\"add:transportLineType\"," +
            "\"view:transportLineTypeDetail\",\"update:transportLineType\",\"delete:transportLineType\"," +
            "\"view:transportLine\",\"add:transportLineManger\",\"delete:transportLine\"," +
            "\"view:trips\",\"add:trips\",\"update:trips\",\"delete:trips\",\"view:tripsDetail\"," +
            "\"add:tripsTruckDriver\",\"view:transportTaskManager\",\"view:transportTaskManagerDetail\"," +
            "\"view:driverJobManager\",\"update:transportLineManage\",\"view:transportLineDetail\"," +
            "\"view:scheduleList\",\"add:scheduleDispatch\",\"add:scheduleRun\",\"add:schedulePause\"," +
            "\"add:scheduleResume\",\"add:driverInfo\",\"view:scheduleLog\",\"view:scheduleLogDetail\"," +
            "\"view:truckTransportTrips\",\"add:taskManager\",\"view:queryLocus\",\"view:truckPlace\"," +
            "\"view:truckPlaceInfo\",\"view:orderLocus\",\"view:selectByList\",\"view:orderLocusPoint\"," +
            "\"view:taskPoint\"";

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    JwtUtils jwtUtils;
    /**
     * 登录接口
     * @param vo
     * @return
     */
    @Override
    public R<LoginRespVo> login(LoginReqVo vo){
        if (Objects.isNull(vo.getAccount())||Objects.isNull(vo.getCode())||Objects.isNull(vo.getPassword())||Objects.isNull(vo.getKey())){
            return R.error("参数异常");
        }
        //验证码校验
        String key = "code:"+vo.getKey();
        String s = redisTemplate.opsForValue().get(key);
        String code = vo.getCode();
        System.out.println(vo.getCode()+" "+s+" "+vo.getCode().equals(s));
        if (s==null||!s.equals(vo.getCode())){
            return R.error("验证码错误");
        }
        //账号密码查询（启用状态）
        PdAuthUser user = pdAuthUserDao.selectUserByAccountAndPassword(vo.getAccount(),vo.getPassword());
        if (Objects.isNull(user)){
            return R.error("请核对后再登录");
        }

        LoginRespVo loginRespVo = new LoginRespVo();
        // 1. 初始化
//        JwtUtils jwtOperator = new JwtUtils();
//        jwtOperator.expirationTimeInSecond = 1209600L;
//        jwtOperator.secret = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt";

        // 2.设置用户信息
        HashMap<String, Object> objectObjectHashMap = Maps.newHashMap();
        if (Objects.nonNull(user.getId())){
        objectObjectHashMap.put("id", user.getId());}
        if (Objects.nonNull(user.getAccount())){
        objectObjectHashMap.put("account", user.getAccount());}
        if (Objects.nonNull(user.getOrgId())){
        objectObjectHashMap.put("org_id",user.getOrgId());}
            if (Objects.nonNull(user.getStationId())){
        objectObjectHashMap.put("station_id",user.getStationId());}
        // 测试1: 生成token
        String token = jwtUtils.generateToken(objectObjectHashMap);
        // 会生成类似该字符串的内容: eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ
        System.out.println(token);
        //生成token
        UserToken userToken = new UserToken();
        userToken.setToken(token);
        //待定
        userToken.setExpire("43200");
        loginRespVo.setToken(userToken);
        GetSex getSex = new GetSex(user.getSex());
        PdAuthUserMapEntity conver = PdAuthUserMap.INSTANCT.conver(user);
        conver.setSex(getSex);
        conver.setStatus(Integer.parseInt(user.getStatus()) == 1);
        conver.setLastLoginTime(new Date());
        user.setLastLoginTime(new Date());
        List<String> strings = new ArrayList<>(Arrays.asList(permissionsList.split(",")));
        //构建返回对象
        loginRespVo.setUser(conver);
        loginRespVo.setPermissionsList(strings);

        return R.ok("成功",loginRespVo,null,null,String.valueOf(System.currentTimeMillis()),false,true);
    }
}
